package com.uchedao.vehicledetection.view.accident;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.view.LayoutInflater;

import com.nostra13.universalimageloader.utils.L;
import com.uchedao.vehicledetection.R;
import com.uchedao.vehicledetection.activity.ImagePagerActivity;
import com.uchedao.vehicledetection.adapter.SkeletonAdapter;
import com.uchedao.vehicledetection.db.DbHelper;
import com.uchedao.vehicledetection.global.GlobalInfo;
import com.uchedao.vehicledetection.inf.IOnResultBack;
import com.uchedao.vehicledetection.loadstate.UCheDaoRelativeLayout;
import com.uchedao.vehicledetection.model.Accident;
import com.uchedao.vehicledetection.model.Draft;
import com.uchedao.vehicledetection.model.Skeleton;
import com.uchedao.vehicledetection.utils.Util;
import com.uchedao.vehicledetection.view.widget.stickylistheaders.StickyListHeadersListView;

import java.io.File;

/**
 * Description:结构件view
 * <p/>
 * Date: 2015-09-16  10:07
 * User: wushan
 */
public class AccidentSkeletonView extends UCheDaoRelativeLayout implements SkeletonAdapter.SkeletonAdapterListener,IOnResultBack {

    public static final int FROM_CAMERA_SKELETON = 201;// 拍照获取

    public static final int FROM_PICTURE_SKELETON = 202;// 从图库获取

    public static final int FROM_PIC_VIEWPAGER_SKELETON = 203;// 从图片浏览返回


    private Accident accident;

    private String tmpPath;// 临时图片路径

    private AlertDialog pickerDialog;// 图片选取对话框

    private Skeleton tmpSkeleton;

    private SkeletonAdapter skeletonAdapter;

    public AccidentSkeletonView(Context context) {
        super(context);
    }

    public AccidentSkeletonView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AccidentSkeletonView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean save() {


        //TODO 需要单独保存cover
        ContentValues values = new ContentValues();
        values.put(DbHelper.KEY_DRAFT_ACCIDENT, toJson(accident));
        accident.skeletonsInt = 1;

        int status = GlobalInfo.draft.status[Draft.TYPE_ACCIDENT];

        if( accident.coverInt +accident.reinforcementInt+accident.skeletonsInt==3){
            values.put(DbHelper.KEY_DRAFT_ACCIDENT_STATUS, Draft.STATUE_FINISH);
            status = Draft.STATUE_FINISH;
        }

        // 若原先状态为未完成，且数据已变动，则状态改变为已完成
//        if (GlobalInfo.draft.status[Draft.TYPE_ACCIDENT] != Draft.STATUE_FINISH) {
//            values.put(DbHelper.KEY_DRAFT_ACCIDENT_STATUS, Draft.STATUE_FINISH);
//            status = Draft.STATUE_FINISH;
//        }

        // 保存成功
        if (GlobalInfo.dbHelper.updateDraf(GlobalInfo.draft.car_plate, values)) {
            GlobalInfo.draft.accident = accident.clone();
            GlobalInfo.draft.status[Draft.TYPE_ACCIDENT] = status;
            return true;
        }

        return false;
    }

    @Override
    public boolean dataChanged() {
        return !toJson(accident).equals(toJson(GlobalInfo.draft.accident));
//        return false;
    }

    @Override
    public void initView() {
        LayoutInflater.from(mContext).inflate(R.layout.view_detection, this);
        StickyListHeadersListView stickListHeadersListView = (StickyListHeadersListView) findViewById(R.id.detection_listView);
        skeletonAdapter = new SkeletonAdapter(mContext, getSkeletonData(), this);
        skeletonAdapter.setResultTvWidth(Util.sp2px(mContext, 18) * 7);
        stickListHeadersListView.setAdapter(skeletonAdapter);
    }

    @Override
    public void initDataAfterView() {

    }

    @Override
    public void initListener() {

    }

    /**
     * 得到结构件数据
     *
     * @return
     */
    private Skeleton[] getSkeletonData() {
        
        String[] headers = GlobalInfo.resources.getStringArray(R.array.skeleton_tabspec_entries);

        int[] arrayId = {R.array.skeleton_engine_entries, R.array.skeleton_front_beam_entries,
                R.array.skeleton_safety_post_entries, R.array.skeleton_behind_beam_entries,
                R.array.skeleton_behind_box_entries};

        String[] numbers = GlobalInfo.resources.getStringArray(R.array.skeleton_keys);
        accident =  GlobalInfo.draft.accident.clone();
        
        for (int i = 0, k = 0; i < headers.length; i++) {
            String[] texts = GlobalInfo.resources.getStringArray(arrayId[i]);
            for (String text : texts) {
                if (accident.skeletons[k] == null)
                    accident.skeletons[k] = new Skeleton();
                accident.skeletons[k].header = headers[i];
                accident.skeletons[k].name = text;
                accident.skeletons[k].number = numbers[k];
                k++;
            }
        }
        return accident.skeletons;
    }

    /**
     * 显示图片选取对话框
     */
    public void showPickerDialog() {
        System.out.println("ws-----回调回来了");
        if (pickerDialog == null) {
            CharSequence[] items = {"拍照", "从图片库选择"};
            pickerDialog = new AlertDialog.Builder(mContext).setTitle("选择")
                    .setItems(items, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == 0) {
                                Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                                File file = new File(GlobalInfo.PIC_PATH, System.currentTimeMillis() + ".jpg");
                                tmpPath = file.getAbsolutePath();
                                Uri uri = Uri.fromFile(file);
                                i.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                                Context context = getContext();
                                if (context instanceof Activity) {
                                    Activity activity = (Activity) context;
                                    activity.startActivityForResult(i, FROM_CAMERA_SKELETON);
                                }


                            } else {

                                Intent intent = new Intent();
                                /* 开启Pictures画面Type设定为image */
                                intent.setType("image/*");
                                /* 使用Intent.ACTION_GET_CONTENT这个Action */
                                // intent.setAction(Intent.ACTION_GET_CONTENT);
                                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                                    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                                } else {
                                    intent.setAction(Intent.ACTION_GET_CONTENT);
                                }
                                /* 取得相片后返回本画面 */
                                Context context = getContext();
                                if (context instanceof Activity) {
                                    Activity activity = (Activity) context;
                                    activity.startActivityForResult(intent, FROM_PICTURE_SKELETON);
                                }

                            }
                        }
                    }).create();
        }
        pickerDialog.show();

    }

    public void onActivityResultView(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {

            switch (requestCode) {
                case FROM_CAMERA_SKELETON:// 相机
                    tmpSkeleton.pic_path_list.add(tmpPath);
                    skeletonAdapter.notifyDataSetChanged();
                    break;

                case FROM_PICTURE_SKELETON:// 图库
                    Uri uri = data.getData();
                    tmpPath = Util.getPath(mContext, uri);
                    L.i("uri = " + uri.toString() + " path=" + tmpPath);
                    tmpSkeleton.pic_path_list.add(tmpPath);
                    skeletonAdapter.notifyDataSetChanged();
                    break;

                case FROM_PIC_VIEWPAGER_SKELETON:// 图片浏览
                    tmpSkeleton.pic_path_list = data.getStringArrayListExtra("pic_path_list");
                    skeletonAdapter.notifyDataSetChanged();
                    break;
            }

        }

    }

    @Override
    public void onPhotoAdd(Skeleton skeleton) {
        tmpSkeleton = skeleton;
        showPickerDialog();
    }

    @Override
    public void onPhotoEdit(Skeleton skeleton) {
        tmpSkeleton = skeleton;
        // 图片浏览软件
        Intent intent = new Intent(mContext, ImagePagerActivity.class);
        intent.putExtra("title", skeleton.name);
        intent.putStringArrayListExtra("pic_path_list", skeleton.pic_path_list);

        Context context = getContext();
        if (context instanceof Activity) {
            Activity activity = (Activity) context;
            activity.startActivityForResult(intent, FROM_PIC_VIEWPAGER_SKELETON);
        }

    }
}
